Do you find this program a little bit confusing?

Answer:

Yes—something about all those IFs...

The IF-ELSEIF Structure

Its not just you. Other people find this confusing. When things are nested three deep (an IF inside an IF inside an IF), everyone gets a little uneasy. Luckily QBasic has a special control structure that helps this. The IF-ELSEIF structure looks like this:

IF condition-1 THEN
  branch-1
ELSEIF condition-2 THEN
  branch-2
ELSEIF condition-3 THEN
  branch-3
. . .

ELSEIF condition-n THEN
  branch-n
ELSE
  else-branch
END IF

Here is how this structure works:

  1. Each branch is a possible choice.
  2. Only 1 choice will be made.
  3. You can have as many ELSEIF sections as you want.
  4. Each condition is an expression that gives true/false (just like in ordinary IF statements.)
  5. Each branch is one or many QBasic statements (just like the true or false branch of ordinary IF statements.)
  6. Here is how the 1 choice is made among all the branches:
    • The conditions are tested one-by-one starting with condition-1.
    • The first true condition will have its branch executed.
    • If no condition is true then the else-branch will execute.
    • After the chosen branch has executed, the next statement to execute will be the one that follows the END IF (so no other branch will execute.)

You don't have to have an ELSE and its else-branch. If you omit them, then if no condition is true no branch at all will execute.

The ELSEIF structure is an extension to the fundamental IF-THEN-ELSE-END IF structure. You don't really need it, but sometimes it is very convenient.

QUESTION 11:

If your program needs to choose several options from many possibilities, can this structure be used?